<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:leave:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:leave:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:leave:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:leave:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!--请假天数-->
    <!-- 新增统计卡片 -->
    <el-row :gutter="20" class="mb8">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">本月累计请假天数</div>
          <div class="stat-value">{{ monthlyLeaveDays }} 天</div>
        </el-card>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="leaveList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="用户ID" align="center" prop="userId" v-if="false"  />
      <!--<el-table-column label="审批人ID" align="center" prop="approverId"  v-show="false" />-->
      <el-table-column label="审批人" align="center" prop="approverName" />
      <el-table-column label="请假类型" align="center" prop="leaveType" v-if="false" />
      <el-table-column label="请假开始日期" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假结束日期" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假天数" align="center" prop="leaveDays" />
      <el-table-column label="请假原因" align="center" prop="reason" v-if="false" />
      <el-table-column label="审批状态" align="center">
        <template #default="{ row }">
          <el-button
            class="uniform-btn"
            :class="{
        'pending-btn': row.status === 'PENDING',
        'approve-btn': row.status === 'APPROVED',
        'reject-btn': row.status === 'REJECTED'
      }"
            :type="{
        'PENDING': 'warning',
        'APPROVED': 'success',
        'REJECTED': 'info'
      }[row.status]"
            @click="showResult(row)"
          >
            <!-- 新增状态映射：将英文状态转为中文 -->
            {{
            {
            APPROVED: '已通过',
            PENDING: '审批中',
            REJECTED: '已拒绝'
            }[row.status]
            }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="审批时间" align="center" prop="approvalTime" width="180" v-if="false" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approvalTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="createdTime" width="180" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedTime" width="180" v-if="false">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批原因" align="center" prop="result"  v-if="false"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            :disabled="scope.row.status !== 'PENDING'"
            :title="scope.row.status !== 'PENDING' ? '非待审批状态不可修改' : ''"
            v-hasPermi="['system:overtimeapply:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:leave:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改请假申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" disabled />
        </el-form-item>
        <!-- 修改审批人表单项 -->
        <el-form-item label="审批人" prop="approverId">
          <el-select
            v-model="form.approverId"
            placeholder="请选择审批人"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="item in managerOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="请假类型" prop="leaveType">
          <el-select
            v-model="form.leaveType"
            placeholder="请选择请假类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in leaveTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="请假开始日期" prop="startDate">
          <el-date-picker clearable
            v-model="form.startDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择请假开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="请假结束日期" prop="endDate">
          <el-date-picker clearable
            v-model="form.endDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择请假结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="请假原因" prop="reason">
          <el-input v-model="form.reason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listLeave, getLeave, delLeave, addLeave, updateLeave, getDeptManagers ,monthlyTotal} from "@/api/system/leave";
export default {
  name: "Leave",
  data() {
    return {
      monthlyLeaveDays: 0,
      managerOptions: [
        { value: 1, label: 'admin' } // 默认选项
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 请假申请表格数据
      leaveList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        approverId: null,
        leaveType: null,
        startDate: null,
        endDate: null,
        leaveDays: null,
        reason: null,
        status: null,
        approvalTime: null,
        createdTime: null,
        updatedTime: null,
        result: null
      },
      // 表单参数
      form: {},
      leaveTypeOptions: [
        { value: 'ANNUAL', label: '年假' },
        { value: 'SICK', label: '病假' },
        { value: 'PERSONAL', label: '事假' },
        { value: 'OTHER', label: '其他' }
      ],
      managerOptions: [],
      // 表单校验
      rules: {
        approverId: [
          { required: true, message: "审批人不能为空", trigger: "change" }
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        leaveType: [
          { required: true, message: "请假类型不能为空", trigger: "change" }
        ],
        startDate: [
          { required: true, message: "请假开始日期不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "请假结束日期不能为空", trigger: "blur" }
        ],
        reason: [
          { required: true, message: "请假原因不能为空", trigger: "blur" }
        ],
      }
    };
  },

  created() {
    this.userId = this.$store.state.user.id;
    this.queryParams.userId = this.userId; // 正确赋值
    this.getList();
    this.getMonthlyTotal(); // 新增调用
  },
  methods: {
    // 新增获取本月请假天数方法
    getMonthlyTotal() {
      monthlyTotal().then(response => {
        this.monthlyLeaveDays = response.data || 0;
    }).catch(error => {
        // console.error('获取本月请假天数失败:', error);
    });
    },
    /** 查询请假申请列表 */
// 修改后的 getList 方法
    getList() {
      this.loading = true;
      listLeave(this.queryParams).then(response => {
        // 计算请假天数
        const calculateDays = (startDate, endDate) => {
        const start = new Date(startDate);
      const end = new Date(endDate);
      // 计算时间差（毫秒）
      const diffTime = Math.abs(end - start);
      // 转换为天数并向上取整，加1包括开始当天
      return Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;
    };

      // 处理数据，添加 leaveDays 属性
      this.leaveList = response.rows.map(item => ({
        ...item,
        leaveDays: calculateDays(item.startDate, item.endDate)
    }));

      this.total = response.total;
      this.loading = false;
    });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        approverId: 1,
        leaveType: null,
        startDate: null,
        endDate: null,
        leaveDays: null,
        reason: null,
        status: null,
        approvalTime: null,
        createdTime: new Date().toISOString().split('T')[0], // 默认今天日期（格式：YYYY-MM-DD）
        updatedTime: new Date().toISOString().split('T')[0], // 默认今天日期（格式：YYYY-MM-DD）
        result: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.userId = this.userId;
      // 先重置为默认选项
      this.managerOptions = [{ value: 1, label: 'admin' }];
      // 获取部门经理并追加
      getDeptManagers(this.userId).then(response => {
        const managers = response.data.map(item => ({
          value: item.userId,
          label: item.nickName
        }));
      // 合并并去重
      this.managerOptions = [
        ...this.managerOptions,
    ...managers.filter(m => m.value !== 1) // 避免重复
    ];
    }).catch(error => {
        console.error('获取部门经理失败:', error);
    });
      this.open = true;
      this.title = "添加请假申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getLeave(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改请假申请";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 🔔 添加提示弹框
          this.$alert('修改审批完成之后就不允许修改，请检查你的请假内容', '注意事项', {
            confirmButtonText: '我知道了',
            callback: () => {
            if (this.form.id != null) {
            // 修改
            updateLeave(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          } else {
            // 新增
            this.form.userId = this.userId;
            if (!this.form.result) {
              this.form.result = "审批还未通过，请耐心等待审批结果";
            }
            addLeave(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
          }
        }
        });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除请假申请编号为"' + ids + '"的数据项？').then(function() {
        return delLeave(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/leave/export', {
        ...this.queryParams
      }, `leave_${new Date().getTime()}.xlsx`)
    },
    showResult(row) {
      this.$alert(row.result || '暂无审批说明', '审批原因', {
        confirmButtonText: '确定'
      });
    },
  }
};
</script>
<style scoped>
  .stat-card {
    margin-bottom: 20px;
    text-align: center;
  }
  .stat-title {
    font-size: 14px;
    color: #909399;
  }
  .stat-value {
    font-size: 24px;
    color: #409EFF;
    margin-top: 10px;
    font-weight: bold;
  }
</style>
